package com.liangdemo.web.thread;


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁
 * 使用lock锁,代替 synchronized 锁 ：实现同步
 */
public class Lock_Condition {
    public static void main(String[] args) {

        String str1 = "1234567890";
        String Str2 = "ABCDEFGHRJK";
        String[] array1 = str1.split("");
        String[] array2 = Str2.split("");

        Lock lock = new ReentrantLock();

        /**
         * 创建两个队列，线程等待休息的时候，可以选择叫醒某一个队列中的线程
         */
        Condition condition1 = lock.newCondition();// 队列， 某种条件下，唤醒
        Condition condition2 = lock.newCondition();

        CountDownLatch latch = new CountDownLatch(1);


        new Thread(() -> {
            try {
                latch.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            lock.lock();
            try {
                for (String a : array1) {
                    System.out.print(a);
                    condition2.signal();//叫醒队列2中的线程
                    condition1.await();//去队列1中休息
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "线程1").start();

        new Thread(() -> {
            lock.lock();

            try {
                for (String b : array2) {
                    System.out.print(b);
                    latch.countDown();
                    condition1.signal();
                    condition2.await();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }


        }, "线程2").start();


    }
}
